from IPython.core.magic import (
    magics_class,
    Magics,
    line_magic,
    cell_magic,
    needs_local_scope
)

from IPython.core import magic_arguments

@magics_class
class MagicOrder(Magics):
    """
    Define customized class which must inherit from Magics and must be declarated by @magics_class
    """

    @line_magic
    def hello(self, line):
        """
        Define a line magic which can be called as below to print the <line of codes>
        %hello <line of codes>
        """
        print(f"line: {line}")

        # Get the local namespace of the shell and excute the codes
        local_ns = self.shell.user_ns
        exec(line, local_ns, local_ns)

    #Use @needs_local_scope to get local namespace
    @line_magic
    @needs_local_scope
    def hello2(self, line,local_ns):
        """
        Define a line magic which can be called as below to print the <line of codes>
        %hello <line of codes>
        """
        # print(f"line: {line}")

        exec(line, local_ns, local_ns)


    #Use 
    @magic_arguments.magic_arguments()
    #define an "name" argument which can be passed as "-n=XXX" or "--name=XXX"
    @magic_arguments.argument("-n","--name",dest="name",default="World")
    @magic_arguments.argument("--age",dest="age", type=int)
    @magic_arguments.argument("-h","--hobby",dest="hobby", default=[],action="append")
    #Use @line_magic to define a line magic
    @line_magic
    #Use @needs_local_scope to get local namespace
    @needs_local_scope
    def hello3(self, line,local_ns):
        """
        Define a line magic which can be called as below to print the <line of codes>
        %hello <line of codes>
        """
        # print(f"line: {line}")

        #exec(line, local_ns, local_ns)

        args = magic_arguments.parse_argstring(self.hello3, line)

        print(args)

        print(args.name)
    
    
    @cell_magic
    @needs_local_scope
    def world(self, line, cell,local_ns):
        """
        Define a cell magic which can be called as below to print the <line of codes>
        %%world
        <line of codes>
        <line of codes>
        """
        # print(f"line: \n{line}")
        # print("-----------------")
        # print(f"cell: \n{cell}")
        exec(cell, local_ns, local_ns)


# define the load function which will be called automatically by %load_ext magic
def load_ipython_extension(ipython):
    ipython.register_magics(MagicOrder)



## Create work/magics/MagicOrder.py
"""
import sys
sys.path.append("/home/jovyan/work/magics")

%load_ext MagicOrder
%reload_ext MagicOrder

%hello a=1
"""